package chapter03;

public class SortedArrayToBST108 {
    /**
     * 中序遍历 总是选择中间位置左边的数字作为根节点
     * process(nums,left,right) 从nums[left,right]选择中间值作为当前子树根节点 递归左孩子和右孩子
     * 递归出口
     *  1).left>right
     *      return null
     *  2).mid=(left+right)/2 找到最左中间值
     *     cur=new TreeNode(nums[mid])
     *     cur.left=process(nums,left,mid-1) 递归左孩子
     *     cur.right=process(nums,mid+1,right) 递归右孩子
     *     return cur 返回根节点
     */
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
           this.val = val;
           this.left = left;
           this.right = right;
       }
   }

    public TreeNode sortedArrayToBST(int[] nums) {
        if(nums.length==0){
            return null;
        }
        int right=nums.length-1;
        int left=0;
        return process(nums,0,right);
    }

    public TreeNode process(int[] nums,int left,int right){
        if(left>right){
            return null;
        }
        int mid=(left+right)/2;
        TreeNode cur=new TreeNode(nums[mid]);
        cur.left=process(nums,left,mid-1);
        cur.right=process(nums,mid+1,right);
        return cur;
    }
}
